<template>
  <div>
    <wk-page-header
      :title="config.showModuleName ? $t('crm.customer.0ef60f491368a988fd912fa3697f5e40') : ''"
      :help="getHelpObj(crmType, 'index')"
      :dropdowns="getDefaultHeaderHandes()"
      @command="pageHeaderCommand">
      <template slot="right">
        <el-button
          v-if="saveAuth"
          type="primary"
          @click="createClick">{{ $t('crm.customer.5743de93e7212e1052359e1f40ab22b3') }}</el-button>
        <el-button
          v-if="indexAuth"
          @click="dupCheckShow = true">{{ $t('crm.customer.708581b07cfe8f4ad04946ca4a9ce0da') }}</el-button>
        <el-button
          v-if="isWxUser"
          @click="getSyncCustomerList">同步企微客户</el-button>
      </template>
    </wk-page-header>

    <div
      v-empty="!indexAuth"
      xs-empty-icon="nopermission"
      :xs-empty-text="$t('crm.customer.ac947487ae64f06c56fe068604d64462')"
      class="crm-container">
      <wk-table-header
        :search.sync="search"
        :tabs="sceneList"
        :active-tab.sync="sceneId"
        :selection-list="tableSelectionList"
        :operations="handleOperations"
        :condition-type-fun="undefined"
        :fields="getFilterFields"
        :props="tableHeaderProps.props"
        :filter-header-props="tableHeaderProps.filterHeaderProps"
        :filter-form-props="tableHeaderProps.filterFormProps"
        :scene-set-props="tableHeaderProps.sceneSetProps"
        :scene-create-props="tableHeaderProps.sceneCreateProps"
        @tabs-change="sceneSelect"
        @operations-click="tableOperationsClick"
        @event-change="tableHeaderHandle"
        @filter-change="handleFilter"
      >
        <template v-if="tableStyleObj.viewType === '2'" slot="custom">
          <el-select
            v-model="activeFlow"
            value-key="flowId"
            class="flow-wrapper">
            <el-option
              v-for="flow in flowList"
              :key="flow.flowId"
              :label="flow.flowName"
              :value="flow" />
          </el-select>
        </template>

        <wk-toggle-button
          v-if="activeFlow"
          v-model="tableStyleObj.viewType">
          <wk-toggle-item value="1">
            <i class="wk wk-icon-three-line" />
          </wk-toggle-item>
          <wk-toggle-item value="2">
            <i class="wk wk-icon-org-solid" />
          </wk-toggle-item>
        </wk-toggle-button>
      </wk-table-header>

      <stage-view
        v-if="tableStyleObj.viewType === '2' && activeFlow"
        :key="`${activeFlow.flowId}${refreshKey}`"
        :base-params="baseParams"
        :flow-item="activeFlow"
        @enter-detail="enterDetail" />

      <template v-else>
        <el-table
          id="crm-table"
          v-loading="loading"
          :row-height="rowHeight"
          :data="list"
          :height="tableHeight"
          :cell-class-name="cellClassName"
          :row-key="`${crmType}Id`"
          :class="crmTableClass"
          :stripe="tableStyleObj.stripe"
          use-virtual
          highlight-current-row
          style="width: 100%;"
          @row-click="handleRowClick"
          @sort-change="sortChange"
          @header-dragend="handleHeaderDragend"
          @selection-change="handleSelectionChange">
          <el-table-column
            show-overflow-tooltip
            reserve-selection
            type="selection"
            fixed
            align="center"
            width="55" />
          <el-table-column
            :resizable="false"
            prop="businessCheck"
            fixed
            label=""
            width="38">
            <template
              slot="header"
              slot-scope="{}">
              <i
                class="wk wk-business"
                style=" color: #9da9c2;cursor: not-allowed;" />
            </template>
            <template slot-scope="scope">
              <el-popover
                :disabled="scope.row.businessCount == 0"
                :offset="250"
                placement="right"
                popper-class="no-padding-popover"
                width="500"
                trigger="click">
                <business-check
                  :data="scope"
                  :show="scope.row.show"
                  @click="relativeBusinessClick"
                  @close="businessClose($event, scope)" />
                <i
                  slot="reference"
                  :style="{'opacity' :scope.row.businessCount > 0 ? 1 : 0}"
                  class="wk wk-business"
                  style="color: #fc6e51;"
                  @click="businessCheckClick($event, scope)" />
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column
            v-if="Show"
            :resizable="false"
            prop="call"
            fixed
            label=""
            width="55">
            <template
              slot="header"
              slot-scope="{}">
              <i
                class="el-icon-phone"
                style="color: #2486e4;cursor: not-allowed; opacity: 0.5;" />
            </template>
            <template slot-scope="scope">
              <el-popover
                placement="right"
                width="500"
                popper-class="no-padding-popover"
                trigger="click"
                @show="showData(scope.row.customerId)"
                @hiden="showCount = -1">
                <call-center
                  :scope="scope"
                  :show="scope.row.customerId === showCount"
                  crm-type="customer"
                  @changeType="changeCRMType" />
                <el-button
                  slot="reference"
                  :style="{'opacity' :scope.$index >= 0 ? 1 : 0}"
                  type="primary"
                  class="wk-call-btn"
                  icon="el-icon-phone"
                  circle
                  @click.stop="callCheckClick($event,scope,scope.$index)" />
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column
            fixed
            width="60">
            <template
              slot="header"
              slot-scope="{}">
              <i class="el-icon-star-off focus-icon is-disabled" />
            </template>
            <template slot-scope="scope">
              <el-tooltip
                :content="scope.row.star == 0 ? $t('crm.customer.d0fb08128b5cf8735c37800a368c8b57') : $t('crm.customer.2c42ca0ed2286c37cccc88b45b39fb6e')"
                effect="dark"
                placement="top">
                <i
                  v-if="scope.row.star == 0"
                  class="el-icon-star-off focus-icon"
                  @click="toggleStar(scope.row)" />
                <i
                  v-else
                  class="wk wk-focus-on focus-icon active"
                  @click="toggleStar(scope.row)" />
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column
            v-for="(item, index) in fieldList"
            :key="index"
            :fixed="item.isLock === 1"
            :prop="item.prop"
            :label="item.label"
            :width="item.width"
            :sortable="item.prop != 'poolDay' ? 'custom' : false"
            :class-name="item.width>60 ? 'column' : '' "
            show-overflow-tooltip>
            <template v-if="item.width>60" slot="otherHeader" slot-scope="{}">
              <el-button
                :icon="item.isLock === 1 ? 'wk wk-unlock' : 'wk wk-lock'"
                class="el-lock-btn"
                type="text"
                @click.stop="fieldFixed(item)" />
              <el-button
                v-if="showFilter(item)"
                class="el-filter-btn"
                type="text"
                icon="wk wk-screening"
                @click.stop="showFilterClick(item)" />
            </template>
            <template slot-scope="{ row, column }">
              <template v-if="item.prop == 'dealStatus'">
                <span :class="row[item.prop] | dealIcon" />
                <span>{{ row[item.prop] | dealName }}</span>
              </template>
              <template v-else-if="item.prop == 'isWxUser'">
                <span v-if="row[column.property]==1">
                  企微客户
                </span>
                <span v-else>
                  系统客户
                </span>
              <!-- <span>{{ ['系统客户', '企微客户'][row[column.property]] }}</span> -->
              </template>
              <template v-else-if="item.prop == 'status'">
                <i
                  v-if="row.status == 2"
                  class="wk wk-circle-password customer-lock" />
              </template>
              <wk-field-view
                v-else
                :props="item"
                :form-type="item.formType"
                :value="row[column.property]">
                <template slot-scope="{}">
                  {{ fieldFormatter(row, column, row[column.property], item) }}
                </template>
              </wk-field-view>
            </template>
          </el-table-column>
          <el-table-column />
          <wk-empty
            slot="empty"
            :props="{
              buttonTitle: $t('crm.customer.ad3cf36186b0f2bca189d7e35f3a9d9d'),
              showButton: saveAuth
            }"
            @click="createClick"
          />
          <field-set
            slot="other"
            :crm-type="crmType"
            @change="setSave" />
        </el-table>

        <div class="p-contianer">
          <el-dropdown trigger="click" placement="top">
            <el-button class="dropdown-btn"><i class="el-icon-s-fold" /></el-button>
            <el-dropdown-menu slot="dropdown" class="wk-table-style-dropdown-menu">
              <el-dropdown-item>
                <span @click.stop>
                  <el-switch v-model="tableStyleObj.rightBorderShow" />
                  {{ $t('crm.customer.24c40d8481822d880816d664a72186cf') }}
                </span>
              </el-dropdown-item>
              <el-dropdown-item>
                <span @click.stop>
                  <el-switch v-model="tableStyleObj.bottomBorderShow" />
                  {{ $t('crm.customer.1b4c70cc1455f82a2c5c37e6dc211c88') }}
                </span>
              </el-dropdown-item>
              <el-dropdown-item>
                <span @click.stop>
                  <el-switch v-model="tableStyleObj.stripe" />
                  {{ $t('crm.customer.d61a4c831ee160b4b03463287fccdd06') }}
                </span>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <el-pagination
            :current-page="currentPage"
            :page-sizes="pageSizes"
            :page-size.sync="pageSize"
            :total="total"
            :pager-count="5"
            class="p-bar"
            layout="prev, pager, next, sizes, total, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
        </div>
      </template>
    </div>

    <!-- 相关详情页面 -->
    <c-r-m-all-detail
      :id.sync="rowID"
      :visible.sync="showDview"
      :crm-type="rowType"
      :model-data="modelData"
      :page-list="crmType == rowType ? list : []"
      :page-index.sync="rowIndex"
      class="d-view"
      @handle="handleHandle" />

    <!-- 新建 -->
    <c-r-m-all-create
      v-if="createShow"
      :crm-type="createType"
      :action="createAction"
      @close="createShow = false"
      @save-success="saveSuccess" />

    <!-- 查重 -->
    <duplicate-check :crm-type="crmType" :visible.sync="dupCheckShow" />

    <!-- 转移 -->
    <transfer-handle
      v-if="transferDialogShow"
      :props="transferHandleProps"
      :dialog-visible.sync="transferDialogShow"
      @handle="handleHandle" />

    <!-- 放入公海 -->
    <put-pool-handle
      :visible.sync="putPoolShow"
      :selection-list="selectionList"
      :crm-type="crmType"
      @handle="handleHandle" />

    <!-- 成交状态 -->
    <deal-status-handle
      :selection-list="selectionList"
      :visible.sync="dealStatusShow"
      @handle="handleHandle" />

    <!-- 团队操作 -->
    <teams-handle
      v-if="teamsDialogShow"
      :props="teamsHandleProps"
      :dialog-visible.sync="teamsDialogShow"
      @handle="handleHandle" />

    <!-- 批量编辑 -->
    <batch-edit
      :selection-list="selectionList"
      :visible.sync="batchEditShow"
      @handle="handleHandle" />
  </div>
</template>

<script>
import {
  crmCustomerTransferAPI,
  crmCustomerSettingTeamSaveAPI,
  crmCustomerSettingTeamDeleteAPI,
  crmCustomerExcelExportAPI,
  crmCustomerDeleteAPI,
  crmCustomerLockAPI
} from '@/api/crm/customer'
import { wechatGetSyncCustomerListAPI } from '@/wechat/api'

import DuplicateCheck from '../components/DuplicateCheck'
import TransferHandle from '@/components/Page/SelectionHandle/TransferHandle' // 转移
import PutPoolHandle from '../components/SelectionHandle/PutPoolHandle' // 放入公海
import DealStatusHandle from '../components/SelectionHandle/DealStatusHandle' // 客户状态修改操作
import BatchEdit from '../components/SelectionHandle/BatchEdit' // 批量编辑
import TeamsHandle from '@/components/Page/SelectionHandle/TeamsHandle' // 操作团队成员
import BusinessCheck from './components/BusinessCheck' // 相关商机
import CallCenter from '@/callCenter/CallCenter'
import CRMAllCreate from '../components/CRMAllCreate'
import { mapGetters } from 'vuex'
import CRMAllDetail from '@/views/crm/components/CRMAllDetail'
import TableMixin from '../mixins/Table'

export default {
  /** 客户管理 的 客户列表 */
  name: 'CustomerIndex',
  components: {
    CRMAllDetail,
    BusinessCheck,
    CallCenter,
    CRMAllCreate,
    DuplicateCheck,
    TransferHandle,
    PutPoolHandle,
    DealStatusHandle,
    TeamsHandle,
    BatchEdit
  },
  filters: {
    dealIcon(statu) {
      return statu == 1 ? 'deal-suc' : 'deal-un'
    },

    dealName(statu) {
      return statu == 1 ? window.app.$t('crm.customer.678fdb886759135e217b1ab7c7951e5b') : window.app.$t('crm.customer.c6eaf3df066106d09eb862215281dcf9')
    }
  },
  mixins: [TableMixin],
  data() {
    return {
      crmType: 'customer',
      showCount: 0,
      createType: 'customer',
      createAction: {
        type: 'save',
        id: '',
        data: {}
      },
      createShow: false,
      modelData: {},
      // 查重
      dupCheckShow: false,
      // 转移
      transferDialogShow: false,
      transferHandleProps: {},
      // 放入公海
      putPoolShow: false,
      // 成交状态修改框
      dealStatusShow: false,
      // 团队展示
      teamsHandleProps: {},
      teamsDialogShow: false,

      batchEditShow: false
    }
  },
  computed: {
    ...mapGetters(['CRMConfig', 'isWxUser']),
    Show() {
      return this.$store.state.crm.isCall
    },
    // 可操作选项
    handleOperations() {
      return this.getOperations([
        'transfer',
        'put_seas',
        'deal_status',
        'export',
        'delete',
        'lock',
        'unlock',
        'add_user',
        'delete_user'
        // 'batch_edit'
      ])
    }
  },
  created() {
    // 该方法里的 this.crmType data() 中不能获取
    // this.tableHeaderProps = this.getTableHeaderProps()
  },
  mounted() {
    this.$nextTick(() => {
      const callOutData = JSON.parse(localStorage.getItem('callOutData'))
      if (callOutData) {
        this.modelData = {
          modelId: callOutData.id,
          model: callOutData.type
        }
      }
    })
  },
  activated() {
    if (this.isRequested) {
      this.getList()
    }
  },
  deactivated() {
  },
  methods: {
    getSyncCustomerList() {
      wechatGetSyncCustomerListAPI().then(res => {
        this.$message.success('数据正在同步，请稍后刷新查看')
        this.getList()
      })
    },
    /**
     * @description: 表头事件
     * @param {*} type
     * @return {*}
     */
    tableOperationsClick(type) {
      if (type === 'transfer') {
        this.transferHandleProps = {
        // 场景编辑请求
          request: crmCustomerTransferAPI,
          params: { ids: this.selectionList.map(item => item[this.crmType + 'Id']) },
          showChangeOwner: true, // 同时变更负责人
          showRemoveType: true, // 是否展示移除操作类型
          // 帮助提示
          help: this.getHelpObj(this.crmType, 'transfer')
        }
        this.transferDialogShow = true
      } else if (type === 'put_seas') {
        // 客户放入公海
        this.putPoolShow = true
      } else if (type === 'deal_status') {
        // 成交状态
        this.dealStatusShow = true
      } else if (type === 'add_user' || type === 'delete_user') {
        // 团队操作
        this.teamsHandleProps = {
          type: {
            add_user: 'add',
            delete_user: 'delete'
          }[type],
          addRequest: crmCustomerSettingTeamSaveAPI,
          removeRequest: crmCustomerSettingTeamDeleteAPI,
          params: { ids: this.selectionList.map(item => item[this.crmType + 'Id']) },
          // 同时添加至联系人
          showAddType: true,
          // 帮助提示
          readOnlyHelp: this.getHelpObj(this.crmType, 'teamReadOnly'),
          readWriteHelp: this.getHelpObj(this.crmType, 'teamReadWrite')
        }
        this.teamsDialogShow = true
      } else if (type === 'export') {
        // 成交状态
        this.$wkExport.export(this.crmType, {
          ...this.getExportFieldRequestData(),
          params: { ids: this.selectionList.map(item => item[`${this.crmType}Id`]) },
          request: crmCustomerExcelExportAPI
        })
      } else if (type === 'delete') {
        this.$confirm(
          this.$t('crm.customer.e65a76c0c06c921f1dbb646c7af08722', { 1: this.selectionList.length }),
          this.$t('crm.customer.2ab51dfe2fcb93cfe22823918923fb21'),
          {
            confirmButtonText: this.$t('crm.customer.a0fe04a16cc65139b37c861e555a03d3'),
            cancelButtonText: this.$t('crm.customer.7dc60ed47c16967101c16776a0b1a9cb'),
            type: 'warning'
          }
        )
          .then(() => {
            this.loading = true
            crmCustomerDeleteAPI(this.selectionList.map(item => item[`${this.crmType}Id`]))
              .then(res => {
                this.loading = false
                this.$message({
                  type: 'success',
                  message: this.$t('crm.customer.88f95d1c9611ada30be8f081a3ff3b8d')
                })
                this.handleHandle({ type })
              })
              .catch(() => {
                // 批量沟通 可能部分删除成功，需要刷新列表
                this.handleHandle({ type })
                this.loading = false
              })
          })
          .catch(() => {})
      } else if (type === 'lock' || type === 'unlock') {
        const message = {
          lock: this.$t('crm.customer.a72416bc07800c0321640b0ca7170751'),
          unlock: this.$t('crm.customer.0a1ead8ead1a357c60c932560cf2b51a')
        }[type]
        this.$confirm(message, this.$t('crm.customer.b42015705f918202500d5fe682baf004'), {
          confirmButtonText: this.$t('crm.customer.b6d70cb805d0fbf70699a7d7f4722d39'),
          cancelButtonText: this.$t('crm.customer.e2d3d1b236649272e35ecb39f33bff40'),
          type: 'warning'
        })
          .then(() => {
            this.loading = true
            crmCustomerLockAPI({
              status: type === 'lock' ? '2' : '1', // 1是正常 2 是锁定
              ids: this.selectionList.map(item => item.customerId).join(',')
            })
              .then(res => {
                this.loading = false
                this.$message({
                  type: 'success',
                  message: this.$t('crm.customer.ec8d283d299e2247cd82eb1ead8d5482')
                })
                this.handleHandle({ type })
              })
              .catch(() => {
                this.loading = false
              })
          })
          .catch(() => {})
      } else if (type == 'batch_edit') {
        this.batchEditShow = true
      }
    },

    // /**
    //  * @description: 表格头部完整配置
    //  * @param {*}
    //  * @return {*}
    //  */
    // getTableHeaderProps() {
    //   const baseProps = this.getBaseTableHeaderProps()
    //   return baseProps
    // },

    /**
     * @description: 相关商机查看
     * @param {*} data
     * @return {*}
     */
    relativeBusinessClick(data) {
      this.rowID = data.businessId
      this.rowType = 'business'
      this.showDview = true
    },

    /**
     * 通过回调控制class
     */
    cellClassName({ row, column, rowIndex, columnIndex }) {
      if (column.property === 'customerName') {
        return 'can-visit--underline'
      } else if (column.property === 'businessCheck') {
        return 'can-visit'
      } else {
        return ''
      }
    },

    /**
     * @description: 商机预览
     * @param {*} e
     * @param {*} scope
     * @return {*}
     */
    businessCheckClick(e, scope) {
      if (scope.row.businessCount == 0) {
        return
      }

      const popoverEl = e.target.parentNode
      this.$set(scope.row, 'show', !scope.row.show)
      popoverEl.__vue__.showPopper = !scope.row.show
    },

    businessClose(e, scope) {
      const popoverEl = e.parentNode
      popoverEl.__vue__.showPopper = false
      this.$set(scope.row, 'show', false)
    },

    /**
     * pover 显示时触发
     */
    showData(val) {
      this.showCount = val
    },

    /**
     * 查看详情
     * @param val
     */
    changeCRMType(val) {
      this.rowType = val.type
      this.rowID = val.id

      this.modelData = {
        modelId: val.id,
        model: val.type
      }

      this.showDview = true

      let callOutData = {
        modelId: val.id,
        model: val.type
      }
      callOutData = JSON.stringify(callOutData)
      localStorage.setItem('callOutData', callOutData)
    },

    /**
     * 解决povper重复的bug
     */
    callCheckClick(e, scope) {
      this.list.forEach(item => {
        this.$set(item, 'callShow', false)
      })
      this.$set(scope.row, 'callShow', !scope.row.callShow)
      const popoverEl = e.target.parentNode
      popoverEl.__vue__.showPopper = !scope.row.callShow
    },

    /**
     * 新建点击
     */
    createClick() {
      this.createType = this.crmType
      this.createAction = {
        type: 'save',
        id: '',
        data: {}
      }
      this.createShow = true
    },

    /**
     * 创建成功
     */
    saveSuccess(data) {
      if (data.type == 'customer') {
        this.handleHandle(data)
        if (data.createContacts) {
          this.createType = 'contacts'
          this.createAction = {
            type: 'relative',
            crmType: 'customer',
            data: {
              customer: data.data
            }
          }
          this.createShow = true
        }
      }
    }

  }
}
</script>

<style lang="scss" scoped>
@import "../styles/table.scss";

::v-deep .el-table th:not(.is-sortable):not(.el-table-column--selection) > .cell {
  display: flex;
  align-items: center;
  font-weight: $--messagebox-font-weight;

  .label {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  &:hover {
    padding-right: 40px !important;

    .caret-wrapper {
      display: inline-flex;
    }
  }

  .caret-wrapper {
    display: none;
    flex-shrink: 0;
  }
}
</style>
